<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-08-16 16:23:49
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\System;

use App\Http\Properties\System\UserProperties;
use App\Http\Services\Service;
use App\Repositories\RoleRepository;
use App\Repositories\UserRepository;
use App\Repositories\MenuRepository;
// use App\Repositories\VerificationCodeRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Repositories\TemporaryTokenRepository;

class UserService extends Service
    {
    public $role_repository;
    public $menu_repository;
    public $T_token;
    public function boot(
        UserRepository $repository,
        RoleRepository $role_repository,
        MenuRepository $menu_repository,
        TemporaryTokenRepository $T_token
        // VerificationCodeRepository $ver_code
    ) {
        $this->repository      = $repository;
        $this->role_repository = $role_repository;
        $this->menu_repository = $menu_repository;
        $this->T_token         = $T_token;
        // $this->ver_code = $ver_code;
        }
    protected function DingTalkAuth()
        {
        $request = request();
        if ($request->has('code') && $request->has('authCode')) {

            $app     = app("DingTalk");
            $dd_user = $app->user->getUserByAuthCode($request->authCode);


            $user = $this->repository->wherePhone($dd_user['mobile'])->getOne();
            if ($user) {
                if (isEmpty($user->union_id)) {
                    $user->union_id = $dd_user['unionId'];
                    }
                if (isEmpty($user->open_id)) {
                    $user->open_id = $dd_user['openId'];
                    }
                $user->save();
                }
            // $token = Str::random(60);
            $resdata = $this->T_token->createToken($user->employee_id, $request->input("os"), $request->ip());

            $resdata['userInfo'] = UserProperties::make($user);
            // $user->api_token = $token;
            // $user->save();

            return $resdata;
            }
        else {
            fail('登录信息不完整,请输入用户名和密码');
            }
        }
    protected function login(Request $request)
        {
        if ($request->has('username') && $request->has('password')) {
            $user = $this->repository->whereUsername($request->input('username'))->getOne();

            if (!$user || !Hash::check($request->password, $user->password)) {
                fail('用户名或密码不正确,登录失败');
                }

            // $token = Str::random(60);
            $resdata = $this->T_token->createToken($user->employee_id, $request->input("os"), $request->ip());

            $resdata['userInfo'] = UserProperties::make($user);
            // $user->api_token = $token;
            // $user->save();

            return $resdata;
            }
        else {
            fail('登录信息不完整,请输入用户名和密码');
            }
        }
    public function info(Request $request)
        {
        if ($request->has("id"))
            $this->repository->whereId($request->input("id"))->first();
        }
    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        // return $this->success($data, "list success!");
        }
    protected function save(Request $request)
        {
        $user = $request->toArray();
        if ($request->has('username') && ($request->has('password') || $request->has('password2'))) {

            if ($request->input('password') != $request->input('password2'))
                fail("两次密码不相同！");
            unset($user['password2']);
            $user['password'] = Hash::make($user['password']);
            }
        $new_role = $user['role'] ?? [];
        $user     = $this->repository->autosave($user);
        $this->repository->saveDataPermission($new_role, $user->id);
        $user->department;
        $user->attachments;
        $user->role;
        return UserProperties::make($user);
        }

    public function reSetPassWord()
        {
        $request = request();
        if ($request->newPassword != $request->confirmNewPassword) {
            fail("两次密码不正确！");
            }
        //带着用户ID，说明不是本人自己改的密码
        if ($request->has('ids')) {
            return (new Collection($request->ids))->map(function ($v)
                {
                return $this->repository->find($v);
                })->filter(function ($user)
                    {
                    $user->password = Hash::make(substr($user->phone, -6));
                    return $user->save();
                    });

            }
        else {
            //不带ID  是自己在前端改的，需要提供密码
            $user = auth()->user();
            if (!Hash::check($request->userPassword, $user->password)) {
                fail("用户当前密码不正确！");
                }
            $user->password = Hash::make($request->newPassword);
            $user->save();
            return $user;
            }

        }
    //获取指定用户的授权访问的菜单
    public function menu(Request $request = null)
        {
        //获取用户角色
        $user_id   = $request != null && $request->has('user_id') ? $request->user_id : auth()->user()->employee_id;
        $roles_ids = $this->repository->role($user_id)->pluck("id");

        //根据角色获取菜单ID
        $menu_ids = null;
        if ($user_id != 1)
            $menu_ids = $this->role_repository->menu($roles_ids->toArray())->pluck("id");
        //根据菜单ID，获取树形菜单
        return $this->menu_repository->getMenuList($menu_ids);
        }
    protected function delete(Request $request)
        {
        $this->repository->whereIn("id", $this->getRequestIds())->getList()->filter(function ($v)
            {
            //删除头像
            $v->attachments->filter(function ($file)
                {
                $file->delete();
                });
            //清空权限组
            $this->repository->saveDataPermission([], $v->id);

            //清空已授权tokens
            $v->tokens->filter(function ($token)
                {
                $token->delete();
                });
            $v->delete();
            });

        return "delete success!";
        }

    protected function allowlogin($disabled)
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($user) use ($disabled)
            {
            $user['disabled'] = $disabled;
            return $user->save();
            });
        }
    }
